<template>
  <div class="app-container">
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :title="type === 'add' ? '新建投资' : '编辑投资'"
      width="800px"
      @close="dialogClose"
      class="aMDialog"
    >
      <div class="container">
        <el-form
          size="mini"
          :inline="true"
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          class="aMFrom"
          @keyup.enter.native="submitHandle()"
          label-width="110px"
        >
          <el-form-item prop="investType" label="投资形式：">
            <el-select
              @change="investTypeHandle"
              size="mini"
              v-model="dataForm.investType"
              placeholder="请选择"
              style="width: 300px"
            >
              <el-option
                :label="item.label"
                :value="item.id"
                v-for="item in typeList"
                :disabled="item.disabled"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="relatedStrategyName" label="关联策略：">
            <div @click="selectStrategyHandle" style="display: inline-block">
              <el-input
                size="mini"
                v-model="dataForm.relatedStrategyName"
                placeholder="请选择"
                readonly
                style="width: 200px"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-arrow-right"
                  :class="
                    realContrastMove
                      ? 'el-icon-circle-close pointer'
                      : 'el-icon-arrow-right'
                  "
                  @click.stop="clearRelatedStrategy"
                  @mouseenter="realContrastMove = true"
                  @mouseleave="realContrastMove = false"
                ></i>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="investName" label="投资名称：">
            <el-input
              size="mini"
              v-model="dataForm.investName"
              placeholder="请输入"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="indexId" label="对标指数：">
            <indexSelectTree
              :width="200"
              size="mini"
              :multiple="false"
              :indexType.sync="dataForm.indexId"
              @getIndexName="getIndexNameHandle"
            ></indexSelectTree>
          </el-form-item>
          <el-form-item prop="investAmount" label="初始金额：">
            <el-input
              size="mini"
              style="width: 300px"
              @change="InputSumHandle('investAmount')"
              v-model="dataForm.investAmount"
              :disabled="dataForm.addType === 1"
              placeholder="请输入"
            >
              <span slot="append">元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="initialNetworth" label="初始净值：">
            <el-input
              size="mini"
              style="width: 200px"
              @change="InputSumHandle('initialNetworth')"
              v-model="dataForm.initialNetworth"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item prop="virNetworth" label="初始净值：">
            <el-input
              size="mini"
              style="width: 200px"
              @change="InputSumHandle('virNetworth')"
              v-model="dataForm.virNetworth"
              placeholder="请输入"
            ></el-input>
          </el-form-item> -->
          <el-form-item prop="initialShare" label="初始份额：">
            <el-input
              size="mini"
              style="width: 300px"
              @change="InputSumHandle('initialShare')"
              v-model="dataForm.initialShare"
              placeholder="请输入"
            >
              <span slot="append">份</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="investTime" label="投资时间：">
            <el-date-picker
              v-model="dataForm.investTime"
              type="date"
              size="mini"
              style="width: 200px"
              placeholder="投资时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item prop="addType" label="数据采集方式：">
            <el-select
              v-model="dataForm.addType"
              @change="addTypeHandle"
              placeholder="请选择"
              size="mini"
              style="width: 300px"
            >
              <el-option
                :label="item.label"
                :value="item.id"
                :disabled="item.disabled"
                v-for="item in addTypeList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="investTime" label="投资状态：">
            <el-select
              v-model="dataForm.investStatus"
              placeholder="请选择"
              size="mini"
              style="width: 200px"
            >
              <el-option
                :label="item.label"
                :value="item.id"
                :disabled="item.disabled"
                v-for="item in investStatusOpt"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="isClearNetworth"
            label="清空原有净值"
            v-if="type === 'update' && isClearNetworthShow"
          >
            <el-checkbox v-model="dataForm.isClearNetworth"></el-checkbox>
          </el-form-item>
          <el-form-item
            prop="organId"
            label="邮件模板："
            v-if="dataForm.addType === 3"
          >
            <el-select
              v-model="dataForm.organId"
              placeholder="请选择"
              size="mini"
              style="width: 300px"
            >
              <el-option
                :label="item.label"
                :value="item.id"
                v-for="item in emailOption"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="mark" label="备注：">
            <el-input
              size="mini"
              v-model="dataForm.mark"
              placeholder="请输入备注"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <!-- 添加子投资 -->
          <div class="card-list" v-if="dataForm.investType === 1">
            <div class="tit">子投资分类（必填）</div>
            <div
              class="card-list-content"
              v-for="(item, i) in dataForm.childTypeList"
              :key="item.id"
            >
              <div class="card-list-title">
                <el-form-item
                  label-width="90px"
                  :prop="`childTypeList.${i}.classfyName`"
                  label="分类名称："
                >
                  <el-input
                    :class="{ border_red: item.classfyNameRule }"
                    v-model="item.classfyName"
                    @input="checkNoEmpty(i, 'classfyName')"
                    placeholder="请输入"
                    style="width: 200px"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label-width="83px"
                  :prop="`childTypeList.${i}.indexType`"
                  label="对标指数："
                >
                  <indexSelectTree
                    :class="{ border_red: item.indexTypeRule }"
                    :width="200"
                    refName="cascader1"
                    size="mini"
                    @getIndexName="checkNoEmpty(i, 'indexType')"
                    :multiple="false"
                    :indexType.sync="item.indexType"
                  ></indexSelectTree>
                </el-form-item>
                <div style="width: 100px">
                  <el-button
                    size="mini"
                    style="padding: 4px 10px; height: 28px; margin-right: 5px"
                    v-show="dataForm.childTypeList.length > 1"
                    @click="delectClassfyHandle(i)"
                  >
                    <i class="iconfont icon-ashbin"></i>
                    删除分类
                  </el-button>
                </div>
              </div>
              <div class="card-list-content-title">
                <div style="min-width: 40px; text-align: center">移动</div>
                <div style="min-width: 500px">子投资名称</div>
                <div style="min-width: 100px">操作</div>
              </div>
              <div
                class="card-list-content-child"
                v-for="(citem, index) in item.classifyStrategyExt"
                :key="citem.id"
              >
                <div
                  class="handle-move"
                  style="min-width: 40px; text-align: center"
                >
                  <i class="iconfont icon-tuodongweizhi icon-move"></i>
                </div>
                <el-form-item
                  style="margin: 0"
                  :prop="`childTypeList.${i}.classifyStrategyExt.${index}.strategyName`"
                  label=""
                >
                  <div @click="selectSubInvestHandle(i, index, 'radio')">
                    <el-input
                      v-model="citem.strategyName"
                      :class="{ border_red: citem.strategyNameRule }"
                      @input="
                        checkNoEmpty(
                          i,
                          'strategyName',
                          'classifyStrategyExt',
                          index
                        )
                      "
                      placeholder="请选择子投资"
                      style="width: 500px"
                      suffix-icon="el-icon-arrow-right"
                    ></el-input>
                  </div>
                </el-form-item>
                <div style="min-width: 100px">
                  <el-button
                    size="mini"
                    style="padding: 4px 10px; height: 28px; margin-right: 5px"
                    v-show="
                      dataForm.childTypeList[i].classifyStrategyExt.length > 1
                    "
                    @click="delClassfyChildHandle(i, index)"
                  >
                    <i class="iconfont icon-ashbin"></i>
                    删除
                  </el-button>
                </div>
              </div>
              <div style="display: flex; justify-content: space-between">
                <el-button
                  size="mini"
                  @click="selectSubInvestHandle(i, 0, 'check')"
                  style="width: 48%; margin: 10px 1% 0 1%; border-style: dashed"
                >
                  <i class="iconfont icon-add-circle"></i>
                  添加子投资
                </el-button>
                <el-button
                  size="mini"
                  @click="addOrUpdateHandle(i, 0, 'check')"
                  style="width: 48%; margin: 10px 1% 0 1%; border-style: dashed"
                >
                  <i class="iconfont icon-add-circle"></i>
                  新建子投资
                </el-button>
              </div>
            </div>
            <el-button
              @click="addClassfyHandle"
              style="width: 100%; margin-top: 16px"
            >
              <i class="iconfont icon-add-circle"></i>
              添加子投资分类
            </el-button>
          </div>
          <!-- 添加期货账号 -->
          <div class="card-list" v-if="dataForm.addType === 1">
            <div class="tit">期货账号（必填）</div>
            <div
              style="padding: 0"
              class="card-list-content"
              v-for="(item, i) in dataForm.accounts"
              :key="item.id"
            >
              <div class="card-list-title">
                <el-form-item
                  label-width="70px"
                  :prop="`accounts.${i}.account`"
                  :label="'账号' + (i + 1) + '：'"
                >
                  <el-input
                    v-model="item.account"
                    :class="{ border_red: item.accountRule }"
                    @input="checkNoEmptyAccount(i, 'account')"
                    placeholder="请输入"
                    style="width: 140px"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label-width="70px"
                  :prop="`accounts.${i}.password`"
                  label="密码："
                >
                  <el-input
                    type="password"
                    :class="{ border_red: item.passwordRule }"
                    @input="checkNoEmptyAccount(i, 'password')"
                    v-model="item.password"
                    placeholder="请输入"
                    style="width: 140px"
                  ></el-input>
                </el-form-item>

                <el-form-item
                  label-width="85px"
                  :prop="`accounts.${i}.initAmount`"
                  label="初始金额："
                >
                  <el-input
                    class="append-style"
                    :class="{ border_red: item.initAmountRule }"
                    @change="checkInitAmount(i)"
                    v-model="item.initAmount"
                    placeholder="请输入"
                    style="width: 140px"
                  >
                    <span slot="append">元</span>
                  </el-input>
                </el-form-item>
                <div style="width: 70px">
                  <el-button
                    size="mini"
                    style="padding: 4px 10px; height: 28px; margin-right: 5px"
                    v-show="dataForm.accounts.length > 1"
                    @click="delAccountsHandle(i)"
                  >
                    <i class="iconfont icon-ashbin"></i>
                    删除
                  </el-button>
                </div>
              </div>
            </div>
            <el-button @click="addHandle" style="width: 100%; margin-top: 16px">
              <i class="iconfont icon-add-circle"></i>
              添加期货账号
            </el-button>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" style="width: 100px">
            取 消
          </el-button>
          <el-button type="primary" @click="submitHandle" style="width: 100px">
            确 定
          </el-button>
        </div>
      </div>
    </el-dialog>
    <addOrUpdateOpen
      v-if="addOrUpdateChildView"
      ref="addOrUpdateOpen"
      :userId="userId"
      @closeOpen="selectSubInvestHandle(invest_i, 0, 'check')"
    ></addOrUpdateOpen>
    <strategyOpen
      v-if="strategyVisible"
      ref="strategyOpen"
      title="关联策略"
      type="radio"
      :nolink="true"
      :userId="userId"
      @selctInvestName="selctInvestNameHandle"
    ></strategyOpen>
    <subInvestOpen
      v-if="subInvestVisible"
      ref="subInvestOpen"
      title="子投资列表"
      :type="subInvestType"
      :nolink="true"
      :userId="userId"
      @selctSubInvestName="selctSubInvestName"
      @selCheckctSubInvestName="selCheckctSubInvestName"
    ></subInvestOpen>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

import { addInvest, uptInvest, queryForUpdate } from "@/api/afterInvest";
import {
  INVESTTYPE_OPTIONS,
  ADDTPYEOPTION,
  INVESTSTATUSOPTION,
} from "@/views/afterManage/const";
import strategyOpen from "@/views/afterManage/component/strategyOpen.vue";
import subInvestOpen from "@/views/afterManage/component/subInvestOpen.vue";
import indexSelectTree from "@/components/investComn/indexSelectTree.vue";
import { parseTime } from "@/utils";
import addOrUpdateOpen from "@/views/afterManage/subInvest/addOrUpdateOpen.vue";
import { findAllOrgan } from "@/api/setting";

export default {
  name: "",
  components: { strategyOpen, indexSelectTree, subInvestOpen, addOrUpdateOpen },
  computed: {
    ...mapGetters(["userId"]),
  },

  data() {
    return {
      addOrUpdateChildView: false,
      dialogVisible: false,
      strategyVisible: false,
      subInvestVisible: false,
      typeList: INVESTTYPE_OPTIONS,
      addTypeList: ADDTPYEOPTION,
      investStatusOpt: INVESTSTATUSOPTION,

      isClearNetworthShow: false,
      realContrastMove: false,
      dataForm: {
        investName: "", // 投资名称
        relatedStrategyId: "", // 关联策略id
        relatedStrategyName: "", // 关联策略名称
        organId: "", // 机构邮件模板
        investType: 1, // 投资形式
        indexId: "", //对标指数id
        investAmount: 0, // 初始金额
        initialShare: "", // 初始份额
        initialNetworth: "1", // 初始净值
        virNetworth: "1", // 虚拟净值
        accounts: [], // 期货账号
        investStatus: "", // 投资状态
        investTime: "", //投资时间
        childTypeList: [],
        addType: 2, // 数据采集方式
        investManageType: 1, // 0投前 1投资 2子投资
      },
      emailOption: [],
      strategy_i: 0,
      strategy_index: 0,
      subInvestType: "radio",
      dataRule: {
        investType: [
          { required: true, message: "请选择投资形式", trigger: "change" },
        ],
        investName: [
          { required: true, message: "请输入投资名称", trigger: "blur" },
        ],
        investAmount: [
          { required: true, message: "请输入初始金额", trigger: "blur" },
        ],
        initialShare: [
          { required: true, message: "请输入初始份额", trigger: "blur" },
        ],
        virNetworth: [
          { required: true, message: "请输入虚拟净值", trigger: "blur" },
        ],
        investTime: [
          { required: true, message: "请选择投资时间", trigger: "blur" },
        ],
        organId: [
          { required: true, message: "请选择邮件模板", trigger: "change" },
        ],
      },
      invest_i: 0,
    };
  },
  props: {
    type: {
      type: String,
      default: "add",
    },
    row: {
      type: Array | Object,
    },
    addOrUpdateView: {
      type: Boolean,
    },
  },
  watch: {
    addOrUpdateView: async function (newVal) {
      this.emailOption = await this.getEmailOption();
      this.dialogVisible = newVal;
      if (newVal) {
        this.strategy_i = 0;
        this.strategy_index = 0;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.row.investId) {
            queryForUpdate({
              investId: this.row.investId,
            }).then((res) => {
              console.log(res);
              this.dataForm = {
                mark: res.body.mark,
                investId: res.body.investId,
                investName: res.body.investName,
                relatedStrategyId: res.body.relatedStrategyId,
                relatedStrategyName: res.body.relatedStrategyName,
                investType: res.body.investType,
                organId: res.body.organId,
                indexId: res.body.indexId,
                indexName: res.body.indexName,
                investAmount: res.body.investAmount,
                initialShare:
                  res.body.initialShare ||
                  this.checkNumber(
                    res.body.investAmount * res.body.initialNetworth
                  ),
                virNetworth: res.body.virNetworth || "1",
                initialNetworth: res.body.initialNetworth || "1",
                accounts: res.body.accounts,
                investTime: res.body.investTime,
                childTypeList:
                  res.body.configCompositionVo.strategyClassifyVo || [],
                addType: res.body.addType,
                investStatus: res.body.investStatus,
                investManageType: 1,
              };
            });
          } else {
            this.dataInit();
          }
        });
      }
    },
  },
  created() {},
  methods: {
    dataInit() {
      this.dataForm = {
        investName: "",
        relatedStrategyId: "",
        relatedStrategyName: "",
        investType: 1,
        indexId: "",
        mark: "",
        indexName: "",
        investAmount: 0,
        accounts: [],
        investStatus: "",
        investTime: "",
        initialShare: "",
        initialNetworth: "",
        virNetworth: "1",
        childTypeList: [
          {
            classfyName: "",
            indexType: "",
            classifyStrategyExt: [],
          },
        ],
        addType: 2,
        investManageType: 1,
      };
    },
    async getEmailOption() {
      const res = await findAllOrgan().then();
      const new_res = res.body.map((item) => {
        item.label = item.organName;
        return item;
      });
      console.log("机构邮件模板", new_res);
      return new_res;
    },
    addHandle() {
      this.dataForm.accounts.push({
        account: "",
        password: "",
        initAmount: 0,
      });
    },
    addClassfyHandle() {
      this.dataForm.childTypeList.push({
        classfyName: "",
        indexType: "",
        classifyStrategyExt: [],
      });
    },
    delAccountsHandle(i) {
      this.$confirm(
        `确认删除期货账号【${this.dataForm.accounts[i].account}】此条数据？`,
        "提示",
        { type: "warning" }
      )
        .then((_) => {
          this.dataForm.accounts.splice(i, 1);
        })
        .catch((_) => {});
    },
    delClassfyChildHandle(i, index) {
      console.log(this.dataForm.childTypeList);
      this.$confirm(
        `确认删除子投资名称【${this.dataForm.childTypeList[i].classifyStrategyExt[index].strategyName}】此条数据？`,
        "提示",
        { type: "warning" }
      )
        .then((_) => {
          this.dataForm.childTypeList[i].classifyStrategyExt.splice(index, 1);
        })
        .catch((_) => {});
    },
    delectClassfyHandle(i) {
      this.$confirm(
        `确认删除分类名称【${this.dataForm.childTypeList[i].classfyName}】此条数据？`,
        "提示",
        { type: "warning" }
      )
        .then((_) => {
          this.dataForm.childTypeList.splice(i, 1);
        })
        .catch((_) => {});
    },
    // 关联策略
    selectStrategyHandle() {
      this.strategyVisible = true;
      this.$nextTick(() => {
        this.$refs.strategyOpen.init();
      });
    },

    selctInvestNameHandle(strategyInfoVo) {
      this.dataForm.relatedStrategyId = strategyInfoVo.strategyId;
      this.dataForm.relatedStrategyName = strategyInfoVo.strategyName;
    },
    // 配置组合
    selectSubInvestHandle(i, index, type) {
      this.strategy_i = i;
      this.strategy_index = index;
      this.subInvestType = type;
      this.subInvestVisible = true;
      this.$nextTick(() => {
        this.$refs.subInvestOpen.init();
      });
    },
    // 子投资组合配置单选
    selctSubInvestName(params) {
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].strategyId = params.investId;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].strategyName = params.investName;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].currentShare = params.currentShare;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].currentEquity = params.currentEquity;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].enterTime = params.enterTime;
      this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].strategyNameRule = false;
      // if (!this.defCreatedTime) {
      if (
        !this.dataForm.investTime ||
        new Date(params.enterTime) < new Date(this.dataForm.investTime)
      ) {
        this.dataForm.investTime = params.enterTime || parseTime(new Date());
      } else {
        this.dataForm.investTime = parseTime(new Date());
      }
      // }
    },
    // 子投资组合配置多选
    selCheckctSubInvestName(checkList) {
      for (var i = 0; i < checkList.length; i++) {
        this.dataForm.childTypeList[this.strategy_i].classifyStrategyExt.push({
          strategyId: checkList[i].investId,
          strategyName: checkList[i].investName,
          enterTime: checkList[i].enterTime,
          currentShare: checkList[i].currentShare,
          currentEquity: checkList[i].currentEquity,
        });
      }
    },
    investTypeHandle() {
      if (this.dataForm.investType === 1) {
        this.dataForm.childTypeList = [
          {
            classfyName: "",
            indexId: "",
            classifyStrategyExt: [{ strategyName: "" }],
          },
        ];
      } else {
        this.dataForm.childTypeList = [];
      }
      this.addTypeList.map((item) => {
        if (item.id === 3) {
          if (
            this.dataForm.investType === 2 ||
            this.dataForm.investType === 5
          ) {
            item.disabled = false;
          } else {
            item.disabled = true;
          }
        }
      });
      this.dataForm.addType = "";
      console.log(this.addTypeList);
    },
    addTypeHandle() {
      this.dataForm.InputHandle = 0;
      this.isClearNetworthShow = true;
      if (this.dataForm.addType === 1) {
        this.dataForm.accounts = [
          {
            account: "",
            password: "",
            initAmount: 0,
          },
        ];
      } else {
        this.dataForm.accounts = [];
      }
      this.$refs["dataForm"].clearValidate("organId");
    },
    InputSumHandle(key) {
      // this.$set(this.dataForm, key, this.checkNumber(this.dataForm[key]));
      // switch (key) {
      //   case "initialShare":
      //     this.dataForm.investAmount = this.checkNumber(
      //       this.dataForm.initialNetworth * this.dataForm.initialShare
      //     );
      //     break;
      //   default:
      //     this.dataForm.initialShare = this.checkNumber(
      //       this.dataForm.investAmount / this.dataForm.initialNetworth
      //     );
      //     break;
      // }

      // 优先改净值
      this.$set(this.dataForm, key, this.checkNumber(this.dataForm[key]));
      switch (key) {
        case "investAmount":
          if(this.dataForm.initialShare) {
            this.dataForm.initialNetworth = this.checkNumber(
              this.dataForm.investAmount / this.dataForm.initialShare
            );
          }
        break;
        case "initialNetworth":
          this.dataForm.initialShare = this.checkNumber(
            this.dataForm.investAmount / this.dataForm.initialNetworth
          );
        break;
        case "initialShare":
          if(this.dataForm.investAmount) {
            this.dataForm.initialNetworth = this.checkNumber(
              this.dataForm.investAmount / this.dataForm.initialShare
            );
          }
        break;
        default: break;
      }
    },
    submitHandle() {
      if (this.checkDataFromSubmit() || this.checkChildTypeListLength()) {
        return;
      }
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          console.log(parseTime(this.dataForm.investTime));
          const data = {
            ...this.dataForm,
            initialNetworth: this.dataForm.initialNetworth,
            userId: this.userId,
            investTime: parseTime(this.dataForm.investTime),
            configCompositionVo: {
              strategyClassifyVo: this.copyArr(this.dataForm.childTypeList),
              strategyCompositionVo: {
                compositionName: this.dataForm.investName,
                createdBy: this.userId,
                investTime: parseTime(this.dataForm.investTime),
                hasClassify: "",
                indexType: this.dataForm.indexId,
                initMoney: 0,
                investManageEquity: this.dataForm.investManageEquity,
                investManageShare: this.dataForm.investManageShare,
                mark: this.dataForm.mark,
                strategyId: "",
                updatedBy: "",
                updatedTime: "",
              },
            },
          };
          console.log(data);
          if (this.type === "add") {
            addInvest(data).then((res) => {
              this.$emit("closeOpen");
              this.dialogClose();
              this.$message({
                message: res.msg,
                type: "success",
              });
            });
          } else if (this.type === "update") {
            uptInvest(data).then((res) => {
              this.$emit("closeOpen");
              this.dialogClose();
              this.$message({
                message: res.msg,
                type: "success",
              });
            });
          }
        }
      });
    },
    checkDataFromSubmit() {
      // 非空校验
      let noEmpty = false;

      /**
       * 总资产金额 与 持仓份额
       */
      this.dataForm.investManageEquity = 0;
      this.dataForm.investManageShare = 0;

      this.dataForm.childTypeList.map((item, i) => {
        for (const key in item) {
          if (key === "classfyName" || key === "indexType") {
            if (!item[key]) {
              noEmpty = true;
              this.$set(this.dataForm.childTypeList[i], `${key}Rule`, true);
            }
          }
        }
        let investManageEquity = 0;
        let investManageShare = 0;
        item.classifyStrategyExt.map((citem, index) => {
          /**
           * 计算总资产金额 与持仓份额
           */
          this.dataForm.investManageEquity += this.checkNumber(
            citem.currentEquity || ""
          );
          this.dataForm.investManageShare += this.checkNumber(
            citem.currentShare || ""
          );
          /** end */
          /** end */
          /**
           * 计算分类 份额 与 权益
           */

          investManageEquity += this.checkNumber(citem.currentEquity || "");
          investManageShare += this.checkNumber(citem.currentShare || "");
          /** end */
          for (const key in citem) {
            if (key === "strategyName") {
              if (!citem[key]) {
                noEmpty = true;
                this.$set(
                  this.dataForm.childTypeList[i].classifyStrategyExt[index],
                  `${key}Rule`,
                  true
                );
              }
            }
          }
        });
        this.$set(
          this.dataForm.childTypeList[i],
          "investManageEquity",
          investManageEquity
        );
        this.$set(
          this.dataForm.childTypeList[i],
          "investManageShare",
          investManageShare
        );
      });
      this.dataForm.accounts.map((item, i) => {
        for (const key in item) {
          if (key === "account" || key === "initAmount" || key === "password") {
            if (!item[key]) {
              console.log(item);
              noEmpty = true;
              this.$set(this.dataForm.accounts[i], `${key}Rule`, true);
            }
          }
        }
      });
      if (noEmpty) {
        console.log(noEmpty);
        this.$message.closeAll();
        this.$message({
          message: "存在未填项",
          type: "warning",
        });
        return true;
      }

      if (this.repeatName()) {
        this.$message.closeAll();
        this.$message({
          message: "组合或分类名称不能重复",
          type: "warning",
        });
        return true;
      }
      return false;
    },
    clearRelatedStrategy() {
      this.dataForm.relatedStrategyId = null;
      this.dataForm.relatedStrategyName = null;
    },
    // 名称重复校验
    repeatName() {
      let nameCheck = false;
      const nameObj = {};
      nameObj[this.dataForm.compositionName] = true;
      this.dataForm.childTypeList.map((item, i) => {
        if (nameObj[item.classfyName]) {
          nameCheck = true;
          this.$set(this.dataForm.childTypeList[i], `classfyNameRule`, true);
        }
        nameObj[item.classfyName] = true;
      });
      const accountsNameObj = {};
      this.dataForm.accounts.map((item, i) => {
        if (accountsNameObj[item.account]) {
          nameCheck = true;
          this.$set(this.dataForm.accounts[i], `accountRule`, true);
        }
        accountsNameObj[item.account] = true;
      });
      return nameCheck;
    },
    checkChildTypeListLength() {
      let check = false;
      this.dataForm.childTypeList.map((item, i) => {
        this.$message.closeAll();
        if (item.classifyStrategyExt.length === 0) {
          this.$message({
            message: "子投资分类至少需要选择一个子投资",
            type: "warning",
          });
          check = true;
        }
      });
      return check;
    },
    // 非空校验
    checkNoEmpty(i, name, childName, index) {
      console.log(this.dataForm.childTypeList[i]);
      if (childName) {
        if (this.dataForm.childTypeList[i][childName][index][name]) {
          this.$set(
            this.dataForm.childTypeList[i][childName][index],
            `${name}Rule`,
            false
          );
        }
      } else {
        if (this.dataForm.childTypeList[i][name]) {
          this.$set(this.dataForm.childTypeList[i], `${name}Rule`, false);
        }
      }
    },
    // 期货账号非空校验
    checkNoEmptyAccount(i, name) {
      if (this.dataForm.accounts[i][name]) {
        this.$set(this.dataForm.accounts[i], `${name}Rule`, false);
      }
    },
    checkInitAmount(i) {
      this.$set(
        this.dataForm.accounts[i],
        "initAmount",
        this.checkNumber(this.dataForm.accounts[i].initAmount)
      );
      this.dataForm.investAmount = 0;
      this.dataForm.accounts.forEach((item) => {
        this.dataForm.investAmount += item.initAmount;
      });
      this.InputSumHandle("investAmount");
    },
    getIndexNameHandle(val) {
      this.dataForm.indexName = val;
    },
    // 过滤非数字
    checkNumber(value) {
      value = value.toString();
      value = value.replace(/[^\d.]/g, "");
      value = value.replace(/^\./g, "");
      value = value.replace(/\.{2,}/g, ".");
      value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      return +value;
    },
    addOrUpdateHandle(i) {
      this.addOrUpdateChildView = true;
      this.invest_i = i;
      this.$nextTick(() => {
        this.$refs.addOrUpdateOpen.init();
      });
    },
    copyArr(arr) {
      const res = [];
      for (let i = 0; i < arr.length; i++) {
        res.push(arr[i]);
      }
      return res;
    },
    dialogClose() {
      this.$emit("update:addOrUpdateView", false);
    },
  },
};
</script>
<style lang="scss">
.aMDialog {
  .el-dialog__header {
    .el-dialog__title {
      font-weight: bold;
    }
    .el-dialog__close {
      font-size: 20px;
    }
  }
  .el-dialog__body {
    padding: 16px 20px;
    color: rgba(0, 0, 0, 0.75);
    border-top: 1px solid #f0f0f0;
  }
}
.aMFrom {
  .el-form-item__error {
    padding-top: 2px;
  }
}
.append-style {
  .el-input-group__append {
    padding: 0 10px;
  }
}
</style>
<style scoped lang="scss">
.app-container {
  .container {
    padding: 0;
  }
  .footer {
    margin-top: 40px;
    text-align: center;
  }
  .card-list {
    border-top: 1px solid rgba(240, 240, 240, 1);
    padding: 15px 0;
    .tit {
      font-size: 18px;
      font-weight: bold;
      color: rgba(0, 0, 0, 0.75);
    }
    .card-list-title {
      display: flex;
      background: #f5f5f5;
      font-weight: bold;
      height: 37px;
      font-size: 14px;
      padding-top: 4px;
      justify-content: space-between;
      .iconfont {
        font-size: 14px;
      }
    }
    &-content {
      margin-top: 14px;
      padding: 0 0 20px 0;
      border: 1px solid #ebebeb;
      &-title {
        margin: 10px;
        display: flex;
        background: #f5f7fa;
        color: #666;
        font-weight: bold;
        line-height: 37px;
        justify-content: space-between;
        border-bottom: 1px solid #ebeef5;
      }
      &-child {
        margin: 6px 10px 0 10px;
        padding-bottom: 6px;
        display: flex;
        border-bottom: 1px solid #ebeef5;
        justify-content: space-between;
        .icon-move {
          cursor: pointer;
          font-size: 21px;
          width: 40px;
          display: inline-block;
          line-height: 28px;
        }
      }
    }
  }
  .card {
    position: relative;
    border: 1px solid #ddd;
    & + .card {
      margin-top: 22px;
    }
    .card-tit {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 34px;
      background: #eee;
      padding: 0 12px;
      font-weight: bold;
      margin-bottom: 22px;
      .close {
        width: 20px;
        line-height: 20px;
        text-align: center;
        background: #ff3300;
        color: #fff;
        border-radius: 50%;
        cursor: pointer;
      }
    }
  }
  .dialog-footer {
    margin-top: 35px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
    text-align: right;
  }
}
</style>
